package copy.express.process.spit.impl.buffer;

import copy.express.pojo.EqualsNode;
import copy.express.pojo.NodeStack;
import copy.express.pojo.NodeType;
import copy.express.pojo.type.Type;
import copy.express.process.spit.ConfirmTypeEndIndex;
import copy.express.process.spit.impl.StringTypeEndIndex;
import copy.tools.StringStrTools;

public class StringMethodTypeIndex extends AbsBufferTypeIndex implements ConfirmTypeEndIndex {
    private static StringMethodTypeIndex stringMethodTypeIndex = new StringMethodTypeIndex();
    private StringMethodTypeIndex() {
    }
    public static ConfirmTypeEndIndex getInstance(){
        return stringMethodTypeIndex;
    }

    private StringTypeEndIndex stringTypeEndIndex = StringTypeEndIndex.getInstance();

    @Override
    public boolean confirmType(char c) {
        return stringTypeEndIndex.confirmType(c);
    }

    @Override
    public int findEndIndex(int start,int pos, char[] chars) {
        int endIndex = stringTypeEndIndex.findEndIndex(start, pos, chars);
        if (endIndex < chars.length){
            if ( chars[endIndex] == '.' ){
                return findRightIndex(endIndex,chars,')')+1;
            }else{
                return endIndex;
            }
        }
        return endIndex;
    }
    private String trimChar(String str){
        if ( str.contains("\\'") ){
            return str.substring(1,str.length()-1);
        }
        return str;
    }
    @Override
    public NodeType createNode(int start, int end, char[] chars) {
        String result = StringStrTools.appendFromStartToEnd(start,end-1,chars);
        if (result.contains("(")){
            int left = result.indexOf("(");
            int right = result.indexOf(")");
            int spot = result.lastIndexOf(".",left);
            String leftStr = result.substring(0,spot);
            leftStr = trimChar(leftStr);
            String methodName = result.substring(spot+1,left);
            String rightStr = result.substring(left+1,right);
            rightStr = trimChar(rightStr);
            //建立节点
            NodeType leftNode = (NodeType) new NodeStack(leftStr,1).pop();
            NodeType rightNode = (NodeType) new NodeStack(rightStr,1).pop();
            return new EqualsNode(leftNode,rightNode, Type.EqualsType.DEFAULT);
        }else{
            return stringTypeEndIndex.createNode(start,end,chars);
        }
    }
}
